//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package upgrade

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/comment_dao"
	"atomgit.com/openlinksaas/api-server/dao/project_board_dao"
	"atomgit.com/openlinksaas/api-server/dao/watch_dao"
)

type UpToVer23 struct{}

func (up *UpToVer23) Exec(ctx context.Context) error {
	err := up.clearCiCdWatch(ctx)
	if err != nil {
		return err
	}
	err = up.clearCicdComment(ctx)
	if err != nil {
		return err
	}
	err = up.clearCiCdInBoard(ctx)
	if err != nil {
		return err
	}
	return dao.VersionDao.Set(ctx, dao.VERSION_KEY_SCHEMA, 23)
}

func (up *UpToVer23) clearCiCdWatch(ctx context.Context) error {
	return watch_dao.MyWatchDao.RemoveCicdTarget(ctx)
}

func (up *UpToVer23) clearCicdComment(ctx context.Context) error {
	err := comment_dao.CommentDao.RemoveCicdTarget(ctx)
	if err != nil {
		return err
	}
	return comment_dao.UnReadDao.RemoveCicdTarget(ctx)
}

func (up *UpToVer23) clearCiCdInBoard(ctx context.Context) error {
	nodeList, err := project_board_dao.NodeDao.ListCicd(ctx)
	if err != nil {
		return err
	}
	for _, node := range nodeList {
		err = project_board_dao.EdgeDao.RemoveByToNode(ctx, node.BoardId, node.NodeId)
		if err != nil {
			return err
		}
		err = project_board_dao.EdgeDao.RemoveByFromNode(ctx, node.BoardId, node.NodeId)
		if err != nil {
			return err
		}
		err = project_board_dao.NodeDao.Remove(ctx, node.ProjectId, node.BoardId, node.NodeId)
		if err != nil {
			return err
		}
	}
	return nil
}
